import 'package:flutter/material.dart';
import '../../models/chat_model.dart';
import '../../utils/cached_image_widget.dart';

class ConsultationHistoryPage extends StatefulWidget {
  const ConsultationHistoryPage({super.key});

  @override
  State<ConsultationHistoryPage> createState() =>
      _ConsultationHistoryPageState();
}

class _ConsultationHistoryPageState extends State<ConsultationHistoryPage> {
  int _selectedIndex = 0;
  String _selectedStatus = '全部';

  // 模拟咨询记录数据
  final List<ConsultationRecord> _consultationRecords = [
    ConsultationRecord(
      id: '1',
      userId: 'current_user',
      consultantId: '301',
      consultantName: '王专家',
      consultantAvatar: '',
      topic: 'Flutter性能优化咨询',
      description: '关于Flutter应用性能优化和内存管理的专业咨询',
      status: ConsultationStatus.completed,
      startTime: DateTime.now().subtract(const Duration(days: 5)),
      endTime: DateTime.now().subtract(const Duration(days: 5, hours: -2)),
      duration: 120,
      amount: 500.0,
      notes: '专家提供了很多实用的优化建议，收获很大',
      rating: 5.0,
      review: '王专家技术很专业，解答很详细，推荐！',
    ),
    ConsultationRecord(
      id: '2',
      userId: 'current_user',
      consultantId: '401',
      consultantName: '李设计师',
      consultantAvatar: '',
      topic: 'UI设计风格指导',
      description: '产品UI设计风格和用户体验优化咨询',
      status: ConsultationStatus.ongoing,
      startTime: DateTime.now().subtract(const Duration(hours: 2)),
      endTime: null,
      duration: 0,
      amount: 300.0,
      notes: null,
      rating: null,
      review: null,
    ),
    ConsultationRecord(
      id: '3',
      userId: 'current_user',
      consultantId: '501',
      consultantName: '张产品经理',
      consultantAvatar: '',
      topic: '产品规划咨询',
      description: '新产品功能规划和市场定位咨询',
      status: ConsultationStatus.pending,
      startTime: DateTime.now().add(const Duration(days: 1)),
      endTime: null,
      duration: 0,
      amount: 400.0,
      notes: null,
      rating: null,
      review: null,
    ),
    ConsultationRecord(
      id: '4',
      userId: 'current_user',
      consultantId: '601',
      consultantName: '陈运营专家',
      consultantAvatar: '',
      topic: '用户增长策略',
      description: '用户获取和留存策略咨询',
      status: ConsultationStatus.cancelled,
      startTime: DateTime.now().subtract(const Duration(days: 3)),
      endTime: null,
      duration: 0,
      amount: 350.0,
      notes: '因时间冲突取消',
      rating: null,
      review: null,
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('咨询记录'),
        backgroundColor: Theme.of(context).primaryColor,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () => _showSearchDialog(),
          ),
          IconButton(
            icon: const Icon(Icons.filter_list),
            onPressed: () => _showFilterDialog(),
          ),
        ],
      ),
      body: Column(
        children: [
          // 状态筛选标签
          Container(
            height: 50,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: 5,
              itemBuilder: (context, index) {
                final statuses = ['全部', '待开始', '进行中', '已完成', '已取消'];
                final colors = [
                  Theme.of(context).primaryColor,
                  Colors.orange,
                  Colors.blue,
                  Colors.green,
                  Colors.red,
                ];

                return _buildStatusChip(
                  statuses[index],
                  index == _selectedIndex,
                  colors[index],
                  () {
                    setState(() {
                      _selectedIndex = index;
                      _selectedStatus = statuses[index];
                    });
                  },
                );
              },
            ),
          ),
          // 统计卡片
          Container(
            margin: const EdgeInsets.all(16),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  Theme.of(context).primaryColor,
                  Theme.of(context).primaryColor.withOpacity(0.8),
                ],
              ),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildStatItem('总咨询', _consultationRecords.length.toString(),
                    Icons.psychology),
                _buildStatItem(
                    '已完成',
                    _consultationRecords
                        .where((r) => r.status == ConsultationStatus.completed)
                        .length
                        .toString(),
                    Icons.check_circle),
                _buildStatItem(
                    '总金额',
                    '¥${_consultationRecords.where((r) => r.status == ConsultationStatus.completed).fold(0.0, (sum, r) => sum + r.amount).toStringAsFixed(0)}',
                    Icons.monetization_on),
              ],
            ),
          ),
          // 咨询记录列表
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              itemCount: _getFilteredConsultations().length,
              itemBuilder: (context, index) {
                final record = _getFilteredConsultations()[index];
                return _buildConsultationItem(record);
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatusChip(
      String label, bool isSelected, Color color, VoidCallback onTap) {
    return Padding(
      padding: const EdgeInsets.only(right: 8),
      child: FilterChip(
        label: Text(
          label,
          style: TextStyle(
            color: isSelected ? Colors.white : Colors.black87,
            fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
          ),
        ),
        selected: isSelected,
        onSelected: (_) => onTap(),
        backgroundColor: Colors.grey[200],
        selectedColor: color,
        checkmarkColor: Colors.white,
      ),
    );
  }

  Widget _buildStatItem(String label, String value, IconData icon) {
    return Column(
      children: [
        Icon(icon, color: Colors.white, size: 24),
        const SizedBox(height: 4),
        Text(
          value,
          style: const TextStyle(
            color: Colors.white,
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        Text(
          label,
          style: const TextStyle(
            color: Colors.white70,
            fontSize: 12,
          ),
        ),
      ],
    );
  }

  Widget _buildConsultationItem(ConsultationRecord record) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      child: ListTile(
        leading: CachedAvatarWidget(
          avatarUrl: record.consultantAvatar,
          size: 50,
        ),
        title: Row(
          children: [
            Expanded(
              child: Text(
                record.topic,
                style: const TextStyle(fontWeight: FontWeight.w500),
              ),
            ),
            _buildStatusChipForRecord(record.status),
          ],
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('咨询师：${record.consultantName}'),
            Text('时间：${_formatDateTime(record.startTime)}'),
            Text('金额：¥${record.amount.toStringAsFixed(0)}'),
            if (record.duration > 0) Text('时长：${record.duration}分钟'),
            if (record.rating != null)
              Row(
                children: [
                  const Icon(Icons.star, color: Colors.amber, size: 16),
                  Text(' ${record.rating!.toStringAsFixed(1)}'),
                ],
              ),
          ],
        ),
        trailing: PopupMenuButton<String>(
          onSelected: (value) {
            if (value == 'detail') {
              _showConsultationDetail(record);
            } else if (value == 'review') {
              _showReviewDialog(record);
            } else if (value == 'cancel') {
              _showCancelDialog(record);
            }
          },
          itemBuilder: (context) => [
            const PopupMenuItem(
              value: 'detail',
              child: Row(
                children: [
                  Icon(Icons.info),
                  SizedBox(width: 8),
                  Text('查看详情'),
                ],
              ),
            ),
            if (record.status == ConsultationStatus.completed &&
                record.rating == null)
              const PopupMenuItem(
                value: 'review',
                child: Row(
                  children: [
                    Icon(Icons.rate_review),
                    SizedBox(width: 8),
                    Text('评价'),
                  ],
                ),
              ),
            if (record.status == ConsultationStatus.pending)
              const PopupMenuItem(
                value: 'cancel',
                child: Row(
                  children: [
                    Icon(Icons.cancel, color: Colors.red),
                    SizedBox(width: 8),
                    Text('取消咨询', style: TextStyle(color: Colors.red)),
                  ],
                ),
              ),
          ],
        ),
        onTap: () => _showConsultationDetail(record),
      ),
    );
  }

  Widget _buildStatusChipForRecord(ConsultationStatus status) {
    String text;
    Color color;

    switch (status) {
      case ConsultationStatus.pending:
        text = '待开始';
        color = Colors.orange;
        break;
      case ConsultationStatus.ongoing:
        text = '进行中';
        color = Colors.blue;
        break;
      case ConsultationStatus.completed:
        text = '已完成';
        color = Colors.green;
        break;
      case ConsultationStatus.cancelled:
        text = '已取消';
        color = Colors.red;
        break;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color),
      ),
      child: Text(
        text,
        style: TextStyle(
          color: color,
          fontSize: 12,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  void _showConsultationDetail(ConsultationRecord record) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) => Container(
        height: MediaQuery.of(context).size.height * 0.8,
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                CachedAvatarWidget(
                  avatarUrl: record.consultantAvatar,
                  size: 60,
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        record.consultantName,
                        style: const TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Text(
                        record.topic,
                        style: const TextStyle(
                          fontSize: 16,
                          color: Colors.grey,
                        ),
                      ),
                    ],
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.close),
                  onPressed: () => Navigator.pop(context),
                ),
              ],
            ),
            const Divider(),
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildDetailItem('咨询主题', record.topic),
                    _buildDetailItem('咨询描述', record.description),
                    _buildDetailItem('状态', _getStatusText(record.status)),
                    _buildDetailItem('开始时间', _formatDateTime(record.startTime)),
                    if (record.endTime != null)
                      _buildDetailItem(
                          '结束时间', _formatDateTime(record.endTime!)),
                    if (record.duration > 0)
                      _buildDetailItem('咨询时长', '${record.duration}分钟'),
                    _buildDetailItem(
                        '咨询费用', '¥${record.amount.toStringAsFixed(0)}'),
                    if (record.notes != null)
                      _buildDetailItem('备注', record.notes!),
                    if (record.rating != null) ...[
                      _buildDetailItem(
                          '评分', '${record.rating!.toStringAsFixed(1)}分'),
                      if (record.review != null)
                        _buildDetailItem('评价', record.review!),
                    ],
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDetailItem(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            label,
            style: const TextStyle(
              fontWeight: FontWeight.bold,
              color: Colors.grey,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            value,
            style: const TextStyle(fontSize: 16),
          ),
        ],
      ),
    );
  }

  void _showReviewDialog(ConsultationRecord record) {
    double rating = 5.0;
    final reviewController = TextEditingController();

    showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) => AlertDialog(
          title: const Text('评价咨询'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text('为 ${record.consultantName} 的咨询服务评分'),
              const SizedBox(height: 16),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: List.generate(5, (index) {
                  return IconButton(
                    icon: Icon(
                      index < rating ? Icons.star : Icons.star_border,
                      color: Colors.amber,
                      size: 32,
                    ),
                    onPressed: () {
                      setState(() {
                        rating = index + 1.0;
                      });
                    },
                  );
                }),
              ),
              const SizedBox(height: 16),
              TextField(
                controller: reviewController,
                maxLines: 3,
                decoration: const InputDecoration(
                  labelText: '评价内容',
                  hintText: '请分享您的咨询体验...',
                  border: OutlineInputBorder(),
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                // 这里应该调用API保存评价
                Navigator.pop(context);
                _showSuccessMessage('评价提交成功');
              },
              child: const Text('提交评价'),
            ),
          ],
        ),
      ),
    );
  }

  void _showCancelDialog(ConsultationRecord record) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('取消咨询'),
        content: Text('确定要取消与 ${record.consultantName} 的咨询吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              // 这里应该调用API取消咨询
              Navigator.pop(context);
              _showSuccessMessage('咨询已取消');
            },
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const Text('确定取消', style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
    );
  }

  void _showSearchDialog() {
    final TextEditingController searchController = TextEditingController();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('搜索咨询记录'),
        content: TextField(
          controller: searchController,
          decoration: const InputDecoration(
            labelText: '搜索关键词',
            hintText: '输入咨询主题或咨询师姓名',
            border: OutlineInputBorder(),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              _showSuccessMessage('搜索功能开发中...');
            },
            child: const Text('搜索'),
          ),
        ],
      ),
    );
  }

  void _showFilterDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('筛选咨询记录'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              title: const Text('按时间排序'),
              subtitle: const Text('最新咨询在前'),
              trailing: const Icon(Icons.arrow_downward),
              onTap: () {
                Navigator.pop(context);
                _showSuccessMessage('已按时间排序');
              },
            ),
            ListTile(
              title: const Text('按金额排序'),
              subtitle: const Text('金额从高到低'),
              trailing: const Icon(Icons.monetization_on),
              onTap: () {
                Navigator.pop(context);
                _showSuccessMessage('已按金额排序');
              },
            ),
            ListTile(
              title: const Text('按评分排序'),
              subtitle: const Text('评分从高到低'),
              trailing: const Icon(Icons.star),
              onTap: () {
                Navigator.pop(context);
                _showSuccessMessage('已按评分排序');
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  List<ConsultationRecord> _getFilteredConsultations() {
    if (_selectedStatus == '全部') {
      return _consultationRecords;
    }

    ConsultationStatus status;
    switch (_selectedStatus) {
      case '待开始':
        status = ConsultationStatus.pending;
        break;
      case '进行中':
        status = ConsultationStatus.ongoing;
        break;
      case '已完成':
        status = ConsultationStatus.completed;
        break;
      case '已取消':
        status = ConsultationStatus.cancelled;
        break;
      default:
        return _consultationRecords;
    }

    return _consultationRecords
        .where((record) => record.status == status)
        .toList();
  }

  String _getStatusText(ConsultationStatus status) {
    switch (status) {
      case ConsultationStatus.pending:
        return '待开始';
      case ConsultationStatus.ongoing:
        return '进行中';
      case ConsultationStatus.completed:
        return '已完成';
      case ConsultationStatus.cancelled:
        return '已取消';
    }
  }

  String _formatDateTime(DateTime dateTime) {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }

  void _showSuccessMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green,
        duration: const Duration(seconds: 2),
      ),
    );
  }
}
